package com.mmall.concurrency.AQS;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class SemaphoreDemo1 {
    private final static int threadCount = 50;

    public static void main(String[] args) throws Exception {

        ExecutorService exec = Executors.newCachedThreadPool();

        //  final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        //  定义一个信号量,每次允许并发20个
        final Semaphore semaphore = new Semaphore(20);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    if (semaphore.tryAcquire(1000,TimeUnit.MILLISECONDS)){
                        test3(threadNum);
                        semaphore.release();
                    }
                } catch (Exception e) {
                    log.error("exception", e);
                }
            });
        }

        exec.shutdown();
    }

    private static void test3(int threadNum) throws Exception {
        Thread.sleep(2000);
        log.info("{}", threadNum);
    }
}
